<!-- WeatherView -->
<template>
    <div class="container">
        <div class="weather-container">
            <div class="search-container">
                <!-- 获取输入信息，并在输入时根据输入信息使用函数查找城市以提示 -->
                <input
                    type="text"
                    placeholder="请输入城市名称"
                    v-model="input_info"
                    @input="handleInput"
                />
                <ul class="search-list" v-if="input_info">
                    <li v-if="searchResults.length === 0 && hasSearched" class="text_lg">
                        <span>似乎没有找到您查找的城市</span>
                    </li>
                    <li
                        v-else
                        v-for="(city, index) in searchResults"
                        :key="index"
                        @click="handleCitySelect(city)"
                        class="text_lg"
                    >
                        <span>{{ city.name }}</span>
                        <span class="city-address">{{ city.address }}</span>
                    </li>
                </ul>
                <!-- 收藏城市 -->
                <ul class="favorite-city"  v-if="favorites.length > 0 && !input_info">
                    <!-- 给每个li添加动画组件 -->
                    <div
                        class="wrapper"
                        v-for="(favoriteCity, index) in favorites"
                        :key="index"
                    >
                        <li class="item text_lg">
                            <!-- 为了显示实时温度，需要从api中获取，所以城市列表应该为城市名称数组 -->
                            <span>{{ favoriteCity }}</span>
                            <span>{{ temps[index] }}度</span>
                            <div class="btn-box">
                                <button @click="handleView(favoriteCity)">
                                    查看
                                </button>
                                <button @click="handleDelete(favoriteCity)">
                                    删除
                                </button>
                            </div>
                        </li>
                    </div>
                </ul>
                <div class="no-favorite-city" v-if="favorites.length === 0 && !input_info">
                    <span>暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。</span>
                </div>
            </div>
            <RouterView />
            <!-- 组件：近期天气 -->
            <h2 class="text_lg">近期天气</h2>
            <RecentWeather />
        </div>
    </div>
</template>
<script setup>
import { RouterView, useRouter } from "vue-router";
import RecentWeather from "@/components/RecentWeather.vue";
import {
    getAdcodeByCity,
    searchCity,
    getTodayWeatherByAdcode,
} from "@/api/getData";
import { useFavoritesStore } from "@/stores/favorites";
import { storeToRefs } from "pinia";
import { ref, onMounted } from "vue";

const router = useRouter();
const input_info = ref("");
const searchResults = ref([]);
const hasSearched = ref(false);
const temps = ref([]);
const favoritesStore = useFavoritesStore();
const { favorites } = storeToRefs(favoritesStore);

/**
 * 根据favorites中的城市名称获取实时温度
 * @param {Array} cities 城市名称数组
 * @returns {Array} 温度数组
 */
const getCityTemps = async (cities) => {
    for (const city of cities) {
        const res = await getTodayWeatherByAdcode(city);
        temps.value.push(res.temperature);
    }
    return temps.value;
};
/**
 * 删除、收藏城市
 * @param {Object} city 城市对象
 */
const handleDelete = (city) => {
    favoritesStore.removeFavorite(city);
};
const handleView = async(city) => {
    const adcode = await getAdcodeByCity(city);
    router.push(`/weather/${adcode}?search=${city}`);
};

// 使用防抖函数来避免频繁请求
let searchTimeout = null;
/**
 * 输入框输入时，使用防抖函数来避免频繁请求
 */
const handleInput = () => {
    if (searchTimeout) {
        clearTimeout(searchTimeout);
    }
    // 如果输入为空，清空搜索结果
    if (!input_info.value) {
        searchResults.value = [];
        hasSearched.value = false;
        return;
    }

    searchTimeout = setTimeout(async () => {
        try {
            const results = await searchCity(input_info.value);
            searchResults.value = results || [];
            hasSearched.value = true;
        } catch (error) {
            console.error("搜索城市失败:", error);
            searchResults.value = [];
            hasSearched.value = true;
        }
    }, 300);
};

/**
 * 处理城市选择
 * @param {Object} city 城市对象
 */
const handleCitySelect = (city) => {
    input_info.value = city.name;
    searchResults.value = [];
    router.push(`/weather/${city.adcode}?search=${city.name}`);
};

onMounted(() => {
    getCityTemps(favorites.value);
});
</script>
<style scoped>
* {
    box-sizing: border-box;
}
.container {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.weather-container {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    margin: 0 102px;
    padding: 10px 160px;
    width: 100%;
}
.search-container {
    padding: 16px 0 0;
    width: 100%;
}
.wrapper {
    position: relative;
    display: block;
    margin-bottom: 10px;
}
.search-container input {
    width: 100%;
    padding: 8px 4px;
    background-color: inherit;
    font-size: 100%;
    outline: none;
    border: none;
    border-bottom: 1px solid #fff;
    color: #fff;
}
.search-container input:focus {
    border-bottom: none;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1),
        0 4px 6px -4px rgba(0, 0, 0, 0.1);
}
.search-list,
.favorite-city {
    width: 100%;
    padding: 8px 0px;
    background-color: inherit;
    font-size: 100%;
    color: #fff;
    list-style: none;
    margin: 0;
}
.favorite-city {
    margin-top: 30px;
}
.search-list {
    margin-top: 10px;
}
.search-list li,
.favorite-city li {
    width: 100%;
    padding: 8px 16px;
    background-color: #004e71;
    display: flex;
    justify-content: space-between;
    transition: width 0.3s ease-in-out;
    z-index: 1;
}
.btn-box {
    position: absolute;
    height: 36px;
    right: 0;
    top: 0;
    display: flex;
    gap: 5px;
    z-index: 0;
    opacity: 0;
    transition: opacity 0.3s;
}
.wrapper:hover .item {
    width: calc(100% - 135px);
}
.wrapper:hover .btn-box {
    opacity: 1;
    z-index: 2;
}
.btn-box button {
    cursor: pointer;
    background-color: #eab308;
    color: #fff;
    border: none;
    width: 55px;
    cursor: pointer;
}
.search-list li {
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
}

.search-list li:hover {
    background-color: #003e5a;
}

.city-address {
    color: #ccc;
    font-size: 14px;
}
.no-favorite-city{
  text-align: center;
  margin-top: 30px;
}
</style>
